package fr.mmt.gisfizz.service;

import fr.mmt.gisfizz.entity.User;
import fr.mmt.gisfizz.repository.RoleRepository;
import fr.mmt.gisfizz.repository.UserRepository;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * User CRUD Service.<br/>
 *
 * @author Mathieu MAST
 */
@Transactional
@Service
@Slf4j
public class UserCrudServiceImpl implements UserCrudService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private RoleRepository roleRepository;

    @Override
    public long count() {
        return userRepository.count();
    }

    @Override
    public void delete(String pk) {
        userRepository.delete(pk);
    }

    @Override
    public void delete(User obj) {
        userRepository.delete(obj);
    }

    @Override
    public Page<User> search(Map<String, String> searchMap, Pageable page) {
        String search = searchMap.get("search");
        if (StringUtils.isEmpty(search)) {
            return userRepository.findAll(page);
        } else {
            return userRepository.search('%' + StringUtils.lowerCase(search) + '%', page);
        }
    }

    @Override
    public User getByPk(String pk) {
        return userRepository.findOne(pk);
    }

    @Override
    public User save(User obj) {
        userRepository.save(obj);
        return obj;
    }
}
